package com.tanjun.data.components;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisDelayQueueUtil {


    @Autowired
    private RedissonClient redissonClient;

    public <T> boolean addDelayQueue(String queueName, long delayTime, TimeUnit timeUnit, T msg) {
        if (!StringUtils.hasText(queueName)) {
            return false;
        }
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueName);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(msg, delayTime, timeUnit);
            log.info("延迟队列添加消息成功,queueName：{},delayTime:{},timeUnit:{},msg:{}", queueName, delayTime, timeUnit, msg);
            return true;
        } catch (Exception e) {
            log.error("延迟队列添加消息失败,queueName：{},delayTime:{},timeUnit:{},msg:{},e:{}", queueName, delayTime, msg, timeUnit, e.getMessage());
            throw e;
        }
    }

    @SneakyThrows
    public <T> T getDelayQueue(String queueName) {
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        return delayedQueue.poll();
    }
}
